var MemberManager = function () {
	
	// 初始化增加用户表单验证
	var addUser = function() {
        var addUserForm = $('#add_user_form');
        var error = $('.alert-danger', addUserForm);
        var success = $('.alert-success', addUserForm);
        jQuery.validator.addMethod( "checkName",function(value,element){       
            var returnMsg=true;    
            var url = "../member/checkUserNameExist.json";
            var param = {
            	userName : value,
            	userId : store.get("userId"),
    			mobile : store.get("mobile"),
    			operflag : $(".operflag").val(),
    			id : $('input[name=id]').val(),
    			accessToken : store.get("access_token")
            };
            var methodType = "POST";
            var fnCallback = function(data){
            	if(data){
            		if(data.code == "000000"){
            			returnMsg = true;
            		}else if(data.code == "2005"){
            			window.location.href = "login.html";
            		}else{
            			returnMsg = false;
            		}
            	}
            };
            ajaxRequest(url , param , methodType, fnCallback,false,false);
            
            return returnMsg;
      
        } ,  "此名称已经被占用！请您更换其它名称");        

        addUserForm.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                userName: {
                    minlength: 2,
                    required: true,
                    checkName : true
                },
                email: {
                    required: true,
                    email: true
                },
                password:{
                	required : true,
                	minlength : 6
                },
                realName: {
                    required: true,
                    minlength:2
                },
                mobile: {
                    required: true,
                    number: true,
                    maxlength: 11
                },
                telephone: {
                    required: false,
                    maxlength:20
                },
            },

            invalidHandler: function (event, validator) { //display error alert on form submit              
                success.hide();
                error.show();
                $('.help-block').css("display","block");
                App.scrollTo(error, -200);
            },

            errorPlacement: function (error, element) { // render error placement for each input type
                var obj = $(element).parent().parent();
                if(!obj.attr("data-error-text")){
                	var errorHtml = '<span class="help-block">'
						+	error.text()
						+'</span>';
                	obj.append(errorHtml);
                	
                	obj.attr("data-error-text",error.text());
                }else if(obj.attr("data-error-text") != error.text()){
                	$(element).parent().next("span").remove()
                	var errorHtml = '<span class="help-block">'
						+	error.text()
						+'</span>';
                	obj.append(errorHtml);
                	
                	obj.attr("data-error-text",error.text());
                }
                
                if(error.text() == ""){
                	$(element).parent().next("span").remove()
                }
                
                $(element).parent().next("span").css("display","block");
            },

            highlight: function (element) { // hightlight error inputs
            	$(element)
                .closest('.form-group').removeClass('has-success');
                $(element)
                    .closest('.form-group').addClass('has-error'); // set error class to the control group   
            },

            unhighlight: function (element) { // revert the change done by hightlight
            	$(element)
                .closest('.form-group').removeClass('has-error'); // set error class to the control group
            },

            success: function (label, element) {
                var icon = $(element).parent('.input-icon').children('i');
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                icon.removeClass("fa-warning").addClass("fa-check");
            },

            submitHandler: function (form) {
                error.hide();
                var url = $('.url').val();
                
                if(url == ""){
                	return;
                }
                
                var param = {
        			"userId" : store.get("userId"),
        			"mobile" : store.get("mobile"),
        			"accessToken" : store.get("access_token"),
        			"member" : $('#add_user_form').serializeObject()
        		};
                var methodType = "POST";
                var fnCallback = function(data){
                	if(data){
                		if(data.code == "000000"){
                			$('#user_modal').modal('hide');
                			refreshTableData();
                		}if(data.code == "2005"){
                			window.location.href = "login.html";
                		}
                		else{
                			util.showMessage(data.message,error);
                		}
                	}
                }
                // 提交表单
                ajaxRequest(url , param , methodType, fnCallback);
            }
        });

    }
	// 初始化弹出窗口
	var initModal = function() {
		$('#user_modal').on('show', function () {
		    $('body', document).addClass('modal-open');
		    $('<div class="modal-backdrop fade in"></div>').appendTo($('body', document));
		});
		$('#user_modal').on('hide', function () {
		    $('body', document).removeClass('modal-open');
		    $('div.modal-backdrop').remove();
		});
	}
	// 显示窗口
	var showModal = function(){
		$('#user_modal').modal('show');
		$('.alert-danger').hide();
		$('.form-group').removeClass('has-error');
		$('.form-group').removeClass('has-success');
		$('.help-block').remove();
	}
	// 初始化数据表格
	var initDataTable = function(){

        var oTable = $('.table').dataTable({
            // set the initial value
            "iDisplayLength": 10,
            "bPaginate": true, //翻页功能
            "bServerSide" : true, // 指定服务器端分页
            "bLengthChange": false, //改变每页显示数据数量
            "bFilter": true, //过滤功能
            "bSort": false, //排序功能
            "bInfo": true,//页脚信息
            "bAutoWidth": true,//自动宽度
            "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
            "bStateSave" : true, // 状态保存
            "sPaginationType": "bootstrap",
            "sAjaxSource" : "/ems/member/getUserList.json", // 数据源
            "oLanguage": {
            	"sUrl" : "/ems/assets/plugins/data-tables/lang/dataTable.cn.txt"
            },
            "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
            	// 删除自带搜索功能
            	$(".dataTables_filter").remove();
            	
                var queryparam = dtUtil.convert_aoData(aoData);
                queryparam.q += "";
                var q = {};
                q.productId = $("#product_id").val();
                q.productName = $("#product_name").val();
                q.skuCode = $("#sku").val();
                q.isCheck = $("#sel_check_status").val();
                q.brandId = $("#sel_brand_name").val();
                queryparam.accessToken = store.get("access_token");
                queryparam.userId = store.get("userId");
                queryparam.mobile = store.get("mobile");
                queryparam.q += JSON.stringify(q);
                oSettings.jqXHR = $.ajax({
                    "dataType" : "json",
                    "contentType" : "application/json;charset=UTF-8",
                    "type" : "GET",
                    "url" : sSource,
                    "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
                    "success" : function(json) {
                    	if(json.code == "2005"){
                    		window.location.href = "login.html";
                    	}else{
                    		dtUtil.successCallback(json, aoData, fnCallback);
                    	}
                    }
                });
            },
            "aoColumns": [{
            	"sTitle" : "用户名",
            	"bSortable" : false,
            	"mData" : "userName"
    		},{
    			"sTitle" : "姓名",
    			"mData" : "realName"
    		},{
    			"sTitle" : "手机号码",
    			"mData" : "mobile"
    		},{
    			"sTitle" : "座机号码",
    			"mData" : "telephone"
    		},{
    			"sTitle" : "邮箱",
    			"mData" : "email"
    		},{
    			"sTitle" : "",
    			"mData" : "id",
    			"mRender" : function(data,type,full){
    				var html = "";
    				if(data == 1){
    					return "";
    				}else{
    					html = '<a href="javascript:;" class="btn default btn-xs green">' 
							+'		<div class="edit"><i class="fa fa-edit"></i>编辑</div>'
							+  '</a>'
							+  '<a href="javascript:;" class="btn default btn-xs black">'
							+      '<div class="delete"><i class="fa fa-trash-o"></i>删除</div>'
							+  '</a>';
    					
    					if(full.status == 1){
    						// 显示禁用
    						html += '<a href="javascript:;" class="btn default btn-xs blue">'
    								+	'<div class="stop"><i class="fa fa-stop"></i>禁用</div>'
    								+'</a>';
    					}else{
    						// 现实启用
    						html +='<a href="javascript:;" class="btn default btn-xs blue">'
    								+	'<div class="play"><i class="fa fa-play"></i>启用</div>'
    								+'</a>';
    					}
    				}
    				return html;
    			}
    		}],
            "aoColumnDefs": [{
                    'bSortable': false,
                    'aTargets': [0]
                }
            ]
        
        });
	};
	
	// 初始化点击事件
	var initClickEvent = function(){
		var tableData = $('.table').dataTable();
		// 编辑按钮
		$(".table").on("click","tr>td>a>div.edit",function(e){
			var rowNode = this.parentNode.parentNode.parentNode;
            var rowData = tableData.fnGetData(rowNode);
            
            showModal();
            $('input[name=id]').val(rowData.id);
            $('input[name=userName]').val(rowData.userName);
            $('input[name=realName]').val(rowData.realName);
            $('input[name=password]').val(rowData.password);
            $('input[name=mobile]').val(rowData.mobile);
            $('input[name=telephone]').val(rowData.telephone);
            $('input[name=email]').val(rowData.email);
            
            $('.url').val("../member/editUser.json");
            $('.operflag').val("1");
		});
		// 删除事件
		$(".table").on("click", "tr>td>a>div.delete",function(e){
			var rowNode = this.parentNode.parentNode.parentNode;
            var rowData = tableData.fnGetData(rowNode);
            
            var url = "/ems/member/deleteUser.json";
            var param = {
            	"id" : rowData.id,
            	"userId" : store.get("userId"),
            	"mobile" : store.get("mobile"),
            	"accessToken" : store.get("access_token")
            };
            ajaxRequest(url,param,"POST",refreshTableData,true);
		});
		// 启用
		$(".table").on("click","tr>td>a>div.play",function(e){
			var rowNode = this.parentNode.parentNode.parentNode;
            var rowData = tableData.fnGetData(rowNode);
            
            var url = "/ems/member/changeUserStatus.json";
            var param = {
            	"id" : rowData.id,
            	"status" : "1",
            	"userId" : store.get("userId"),
            	"mobile" : store.get("mobile"),
            	"accessToken" : store.get("access_token")
            };
            ajaxRequest(url,param,"POST",refreshTableData,true);
		});
		// 禁用
		$(".table").on("click","tr>td>a>div.stop",function(e){
			var rowNode = this.parentNode.parentNode.parentNode;
            var rowData = tableData.fnGetData(rowNode);
            
            var url = "/ems/member/changeUserStatus.json";
            var param = {
            	"id" : rowData.id,
            	"status" : "0",
            	"userId" : store.get("userId"),
            	"mobile" : store.get("mobile"),
            	"accessToken" : store.get("access_token")
            };
            ajaxRequest(url,param,"POST",refreshTableData,true);
		});
		// 新增用户
		$('#add_user').on('click',function (e) {
			showModal();
			$('.url').val("../member/addUser.json");
			$('.operflag').val("0");
        });
	}
	
	// 刷新表格数据
	function refreshTableData(data){
		if(data){
			if(data.code == "000000"){
				var tableData = $('.table').dataTable();
				tableData.fnFilter();
			}else if(data.code == "2005"){
				window.location.href = "login.html";
			}else{
				util.showMessage(data.message,"error");
			}
		}else{
			var tableData = $('.table').dataTable();
			tableData.fnFilter();
		}
	}
	
	/**
	 * ajax 请求
	 * url : url 请求地址
	 * param : 参数
	 * fnCallback : 回调函数
	 */
	function ajaxRequest(url , param , methodType, fnCallback,showMessage,async){
		$.ajax({
			type : methodType,
			url : url,
			data: param,
			async : typeof(async) == "undefined" ? false : async,
			success : function(data){
				if(typeof(fnCallback) != "undefined"){
					if(showMessage){
						util.showMessage("操作成功!");
					}
					fnCallback(data);
				}
				else if(data){
					if(data.code == "000000"){
						util.showMessage("操作成功!");
					}else if(data.code == "2005"){
						window.location.href = "login.html";
					}
					else{
						util.showMessage("操作失败，" + data.message,"error");
					}
				}else{
					util.showMessage("数据错误，请刷新页面重试","error");
				}
			}
		});
	}

    return {

        //main function to initiate the module
        init: function () {
        	initModal();
        	initDataTable();
        	initClickEvent();
        	addUser();
        }

    };

}();